/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package merlion.frm.bpm.session;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import merlion.frm.bpm.entity.SupplierInvoice;
import merlion.frm.bpm.entity.SupplierPaymentRecord;
import merlion.frm.bpm.entity.SupplierReceipt;
import merlion.scm.rmpm.entity.RawMaterialItemLine;
import merlion.scm.rmpm.entity.RawMaterialSalesOrder;

/**
 *
 * @author Yuwei
 */
@Stateless
public class ProcurementBPSessionBean implements ProcurementBPSessionBeanLocal {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public SupplierInvoice saveSupplierInvoice(SupplierInvoice invoice) {
        //invoice.getRmso().setInvoice(invoice);
        return entityManager.merge(invoice);
    }

    @Override
    public Collection<SupplierInvoice> getAllSupplierInvoice() {
        return entityManager.createQuery("SELECT s FROM SupplierInvoice s").getResultList();
    }

    @Override
    public SupplierPaymentRecord saveSupplierPaymentRecord(SupplierPaymentRecord spr) {
        spr.getSupplierInvoice().setSupplierPaymentRecord(spr);
        entityManager.merge(spr);
        return spr;
    }

    @Override
    public Collection<SupplierPaymentRecord> getAllSupplierPaymentRecord() {
        return entityManager.createQuery("SELECT s FROM SupplierPaymentRecord s").getResultList();
    }

    @Override
    public SupplierReceipt saveSupplierReceipt(SupplierReceipt receipt) {
        entityManager.merge(receipt);
        return receipt;
    }

    @Override
    public Collection<SupplierReceipt> getAllSupplierReceipt() {
        return entityManager.createQuery("SELECT s FROM SupplierReceipt s").getResultList();
    }

    @Override
    public Collection<SupplierInvoice> getAllUnpaidSupplierInvoice() {
        return entityManager.createQuery("SELECT s FROM SupplierInvoice s WHERE s.supplierPaymentRecord IS NULL").getResultList();
    }

    @Override
    public SupplierInvoice getSupplierInvoiceById(Long id) {
        return (SupplierInvoice) entityManager.createQuery("SELECT i FROM SupplierInvoice i WHERE i .id = '" + id + "'").getSingleResult();
    }
    @Override
    public SupplierInvoice getSupplierInvoiceByIdStr(String idStr){
        return (SupplierInvoice) entityManager.createQuery("SELECT i FROM SupplierInvoice i WHERE i .supplierInvoiceNo = '" + idStr + "'").getSingleResult();
    }

    @Override
    public Collection<RawMaterialSalesOrder> getAllSalesOrderWOInvoice() {
        return entityManager.createQuery("SELECT so FROM RawMaterialSalesOrder so WHERE so.invoice IS NULL").getResultList();
    }

    @Override
    public Boolean matchSupplierInvoiceItems(SupplierInvoice invoice) {
        ArrayList<RawMaterialItemLine> invItems = new ArrayList<RawMaterialItemLine>(invoice.getItemLines());
        ArrayList<RawMaterialItemLine> soItems = new ArrayList<RawMaterialItemLine>(invoice.getRmso().getItemlines());

        if (invItems.size() != soItems.size()) {
            return false;
        }

        for (int i = 0; i < invItems.size(); i++) {

            RawMaterialItemLine invil = invItems.get(i);
            boolean found = false;
            for (int k = 0; k < soItems.size(); k++) {
                RawMaterialItemLine soil = soItems.get(k);
                if (invil.getRawMaterialSupplyInformation().getRawMaterial().getName().equals(soil.getRawMaterialSupplyInformation().getRawMaterial().getName())
                        && (long) invil.getQty() == (long) soil.getQty()) {
                    found = true;
                }
                if (found) {
                    invItems.remove(i);
                    soItems.remove(k);
                    i = -1;
                    break;
                }
            }
        }
        
        if(soItems.isEmpty() && invItems.isEmpty())
            return true;
        return false;
    }

    @Override
    public Boolean matchSupplierInvoiceTotal(SupplierInvoice invoice) {
        if (invoice.getInvoiceAmount().longValue() == invoice.getRmso().getTotal().longValue()) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean matchSupplierInvoiceCurrency(SupplierInvoice invoice) {
        if (invoice.getCurrency() == invoice.getRmso().getCurrency()) {
            return true;
        }
        return false;
    }
    
    @Override
    public String generateSupplierPaymentRecordId(){
         //Get date YYYYMMDD
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        String frontId = sdf.format(cal.getTime());

        //Query Saleslead table, anything like 'yyMMdd'
        Query query = entityManager.createQuery("SELECT s FROM SupplierPaymentRecord s WHERE s.supplierPaymentRecordId LIKE :p1");
        query.setParameter("p1", "%" + frontId + "%");

        //Get result size
        int size = query.getResultList().size() + 1;
        String backId = String.format("%04d", size);

        //Set new ID to 'YYYYMMDD' + 'size + 1'
        String id = "SPR" + frontId + "/" + backId;
        //return id
        return id;
    }
}
